package com.rpp.utils;

import com.rpp.config.ZookeeperConfig;
import org.I0Itec.zkclient.ZkClient;

import java.util.List;

/**
 * @Description
 * @Author peng
 * @Date 2020/8/10 2:16 下午
 */
public class ZookeeperUtil {

    /**
     * 根据IP和端口到zookeeper连接会话
     *
     * @param ip
     * @param port
     * @return
     */
    public static ZkClient createSession(String ip, Integer port) {
        ZkClient zkClient = new ZkClient(ZookeeperConfig.connectionString);
        System.out.println("zookeeper会话创建成功..");
        return zkClient;
    }

    /**
     * 创建临时服务节点，服务下线会自动剔除服务节点信息
     *
     * @param ip
     * @param port
     */
    public static ZkClient createNode(ZkClient zkClient, String ip, Integer port) {

        //首先创建服务根节点
        boolean exists = zkClient.exists(ZookeeperConfig.SERVER_NODE);
        if (!exists) {
            zkClient.createPersistent(ZookeeperConfig.SERVER_NODE);
        }

        //然后创建服务节点
        String nodeName = "/".concat(ip).concat(":").concat(String.valueOf(port));
        zkClient.createEphemeral(ZookeeperConfig.SERVER_NODE + nodeName, Integer.MAX_VALUE);
        System.out.println("服务临时节点创建完成");

        return zkClient;
    }

    /**
     * 获取指定节点的子节点列表
     *
     * @return
     */
    public static List<String> getChildNode(String connectionString, String node) {
        ZkClient zkClient = new ZkClient(connectionString);
        System.out.println("zookeeper会话创建成功..");

        // 获取子节点列表
        List<String> children = zkClient.getChildren(node);
        System.out.println(children);

        return children;
    }
}
